﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Drawing;

namespace TemplateWeb.Helpers
{
    public class FileHelper
    {
        /// <summary>
        /// Build file name from upload file
        /// </summary>
        /// <returns></returns>
        private static string BuildFileName(HttpPostedFileBase file, string idItem)
        {
            FileInfo f = new FileInfo(file.FileName);
            long ngay = DateTime.Now.ToBinary();
            return idItem + ngay + f.Extension;
        }

        /// <summary>
        /// Convert image to byte array
        /// </summary>
        /// <param name="file">file will be uploaded to server</param>
        /// <param name="idItem">id of item</param>
        /// <param name="buffer">contains byte array after converted</param>
        /// <param name="refName">the name of image item builded base on idItem</param>
        /// <returns></returns>
        private static bool ConvertImage2ByteArray(HttpPostedFileBase file, ref byte[] buffer)
        {
            try
            {
                buffer = new byte[file.ContentLength];
                file.InputStream.Read(buffer, 0, file.ContentLength);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Upload a file without resize image
        /// </summary>
        /// <param name="file"></param>
        /// <param name="basepath"></param>
        /// <param name="iditem"></param>
        /// <param name="oldname"></param>
        /// <param name="refName"></param>
        /// <returns></returns>
        public static bool UploadFile(HttpPostedFileBase file, string basepath, string iditem, string oldname, ref string refName)
        {
            try
            {
                if (file == null)
                {
                    return false;
                }

                // Remove old file
                if (oldname != string.Empty && oldname != "noimages.jpg")
                {
                    DeleteFile(basepath + oldname);
                }

                if (!System.IO.File.Exists(basepath + iditem))
                {
                    FileInfo f = new FileInfo(file.FileName);
                    long ngay = DateTime.Now.ToBinary();
                    refName = iditem + ngay + f.Extension;
                    string fullPath = basepath + refName;
                    if (file == null)
                        return false;
                    byte[] buffer = new byte[file.ContentLength];
                    file.InputStream.Read(buffer, 0, file.ContentLength);
                    FileStream newFile = new FileStream(fullPath, FileMode.Create, FileAccess.Write);
                    newFile.Write(buffer, 0, file.ContentLength);
                    newFile.Close();
                }
                else
                {
                    refName = file.FileName;
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Upload a HttpPostedFileBase file to server
        /// </summary>
        /// <param name="file">file will be uploaded to server</param>
        /// <param name="basepath">base path contains most of image items uploaded to server</param>
        /// <param name="idItem">id of item</param>
        /// <param name="oldName">the current name of image item</param>
        /// <param name="refName">the name of image item builded base on idItem</param>
        /// <returns></returns>
        public static bool UploadFile(HttpPostedFileBase file, string basepath, string idItem, string oldName, int width, int height, ref string refName)
        {
            try
            {
                if (file == null)
                {
                    return false;
                }

                // Remove old file
                if (oldName != string.Empty && oldName != "noimages.jpg")
                {
                    DeleteFile(basepath + oldName);
                }

                byte[] image = null;
                // Build new file name
                refName = BuildFileName(file, idItem);
                // Convert image to byte array
                var result = ConvertImage2ByteArray(file, ref image);

                if (result)
                {
                    ImageEditing imgedit = new ImageEditing();
                    // Convert byte array to image
                    Image sourceImg = imgedit.ByteArrayToImage(image);
                    Image resultimage = sourceImg;
                    int widthToResize = width;
                    int heightToResize = height;

                    try
                    {
                        // Resize image
                        if (sourceImg.Width > widthToResize && sourceImg.Height > heightToResize)
                        {
                            resultimage = imgedit.Resize(widthToResize, heightToResize, sourceImg);
                            if (resultimage != null)
                            {
                                image = imgedit.ImageToByteArray(resultimage);
                                // Upload image to server
                                result = UploadFile(basepath, refName, image);
                            }
                        }
                        else
                        {
                            // Upload image to server
                            result = UploadFile(basepath, refName, image);
                        }
                    }
                    catch (Exception ex)
                    {
                        CommonLogging.Logger.Error(string.Format("Error on UploadFile: {0}", ex.ToString()));
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CommonLogging.Logger.Error(ex.InnerException.Message);
                }
                else
                {
                    CommonLogging.Logger.Error(ex.Message);
                }
            }
            return false;
        }

        /// </summary>
        /// <param name="fileName">filename of file will be uploaded</param>
        /// <param name="buffer">byte array converted from image</param>
        /// <param name="oldname">the current name of image item</param>
        private static bool UploadFile(string basePath, string fileName, byte[] buffer)
        {
            string apPath = basePath + fileName;
            try
            {
                using (FileStream fs = new FileStream(apPath, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    fs.Write(buffer, 0, (int)buffer.Length);
                    fs.Close();
                    fs.Dispose();
                }
                return true;
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    CommonLogging.Logger.Error(ex.InnerException.Message);
                }
                else
                {
                    CommonLogging.Logger.Error(ex.Message);
                }
            }
            return false;
        }

        /// <summary>
        /// Delete image exists on server
        /// </summary>
        /// <param name="filePath"></param>
        public static void DeleteFile(string filePath)
        {
            FileInfo file = new FileInfo(filePath);
            if (file.Exists)
            {
                file.Delete();
            }
        }
    }
}